<template>
  <div>
    <div class="operate">
      <el-button
        link
        type="primary"
        @click="operateRow('add')"
        class="btnhover"
        style="width: 90px; height: 30px; background-color: #ff9900; color: rgba(255, 255, 255, 1)"
        >新增图文</el-button
      >
      <el-button
        link
        type="primary"
        @click="delNotificationAnnouncement('batch')"
        class="btnhover"
        style="width: 90px; height: 30px; background-color: #ff9900; color: rgba(255, 255, 255, 1)"
        >批量删除</el-button
      >
      <el-form>
        <el-form-item label="标题" style="margin-right: 15px; margin-left: 13px">
          <el-input
            v-model="topic"
            placeholder=""
            @keyup.enter="getNotificationAnnouncement"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <el-button @click="getNotificationAnnouncement" class="btn btnsearch">查询</el-button>
      <el-button @click="handleReset" class="btn btnreset">重置</el-button>
    </div>
    <!-- <div class="operate">
      <el-button type="warning" @click="operateRow('add')">新增图文</el-button>
      <el-button class="mr-8" type="warning" @click="delNotificationAnnouncement('batch')"
        >批量删除</el-button
      >
      <el-input class="mr-8 w-200" v-model="topic" placeholder="请输入标题" clearable />
      <el-button type="danger" @click="getNotificationAnnouncement">查询</el-button>
      <el-button class="mr-8" type="default" @click="handleReset">重置</el-button>
    </div> -->
    <div class="mt-16 content">
      <div class="left">
        <div class="flex pd-16">
          <span>分类</span>
          <el-icon class="ml-auto" color="#cc352e" @click="operateNode('add')">
            <Plus />
          </el-icon>
        </div>
        <el-tree :data="treeData" :props="defaultProps" @node-click="handleClick">
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span v-if="node.label !== '全部'">
                <el-icon class="mr-8" color="#cc352e" @click.stop="operateNode('edit', data)">
                  <Edit />
                </el-icon>
                <el-icon color="#cc352e" @click="delTreeNode(data)">
                  <Delete />
                </el-icon>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
      <div class="right">
        <el-table
          :data="tableData"
          v-loading="loading"
          element-loading-text="Loading..."
          :header-cell-style="headerCellStyle"
          height="calc(100vh - 260px)"
          style="width: 100%"
          row-key="id"
          border
          default-expand-all
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="topic" label="标题" />
          <el-table-column prop="imageTextType" label="分类" show-overflow-tooltip>
            <template #default="{ row }">
              {{ imageTextTypeRelate(row) }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="发布时间">
            <template #default="{ row }">
              {{ formatTimestamp(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="发布人" />
          <el-table-column prop="viewerCount" label="阅读人数" />
          <el-table-column prop="isTopping" label="置顶">
            <template #default="{ row }">
              <el-icon @click="topRow(row)" :color="row.isTopping ? '#3C87EF' : '#8E8E8E'">
                <Upload />
              </el-icon>
            </template>
          </el-table-column>
          <el-table-column prop="isDisplayViewer" label="大屏和小程序展示">
            <template #default="{ row }">
              <el-checkbox v-model="row.isDisplayViewer" @change="topChange(row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #default="{ row }">
              <el-button type="primary" link @click="operateRow('edit', row)">编辑</el-button>
              <el-button type="primary" link @click="delNotificationAnnouncement('single', row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="flex mt-16">
          <el-pagination
            class="ml-auto"
            v-model:current-page="currentPage"
            :hide-on-single-page="value"
            v-model:page-size="pageSize"
            :page-sizes="[20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </div>
    </div>
    <el-dialog :title="dialogTitle" v-model="operateVisible" width="50%" destroy-on-close>
      <DynamicForm
        ref="dynamicForm"
        :formObj="state.formData"
        :formItemList="formItemList"
        :rules="state.rules"
        labelWidth="100px"
        autoRules
      />
      <template #footer>
        <span>
          <el-button @click="operateVisible = false">取消</el-button>
          <el-button type="primary" @click="operateNotificationAnnouncement">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog :title="operateNodeTitle" v-model="operateNodeVisible" width="50%" destroy-on-close>
      <el-input v-model="state.currentNode.label" placeholder="请输入分类名称" clearable />
      <template #footer>
        <span>
          <el-button @click="operateNodeVisible = false">取消</el-button>
          <el-button type="primary" @click="commitTreeNode">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import globalApi from '@/api/spb/global'
import notificationAnnouncementApi from '@/api/spb/notificationAnnouncement'
import { formatTimestamp } from '../utls/dateFormat'
import DynamicForm from '../components/DynamicForm.vue'
import { cloneDeep } from 'lodash-es'
const message = useMessage()
const dynamicForm = ref()
const operateVisible = ref(false)
const dialogTitle = ref('')
const tableData = ref([])
let treeData = ref([])
const loading = ref(true) // 列表加载中
const value = ref(true)
const defaultProps = {
  children: 'children',
  label: 'label'
}
const operateNodeTitle = ref('')
const operateNodeVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const topic = ref('')
const rowSelection = ref([])
const noticeType = ref(0)
const state = reactive({
  formData: {},
  rules: {
    imageTextType: [{ required: true, message: '分类不能为空！', trigger: 'change' }],
    topic: [{ required: true, message: '标题不能为空！', trigger: 'blur' }],
    author: [{ required: true, message: '发布人/组织不能为空！', trigger: 'blur' }],
    content: [{ required: true, message: '正文不能为空！', trigger: 'blur' }]
  },
  currentNode: {
    label: ''
  }
})

const formItemList = computed(() => {
  return [
    {
      label: '分类',
      name: 'imageTextType',
      require: true,
      type: 'select',
      labelFiled: 'name',
      valueFiled: 'id',
      options: treeData.value
    },
    {
      label: '标题',
      name: 'topic',
      require: true,
      type: 'input'
    },
    {
      label: '发布人/组织',
      name: 'author',
      require: false,
      type: 'input'
    },
    {
      label: '正文',
      name: 'content',
      require: false,
      type: 'editor',
      height: '150px'
    },
    {
      label: '附件',
      name: 'files',
      require: false,
      type: 'uploadFile'
    }
  ]
})

const headerCellStyle = computed(() => {
  return { background: '#f0f0f0' }
})

// 获取通知公告的字典数据
function getDictData() {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_image_text_type'
  }
  globalApi.getDictData(params).then((res) => {
    treeData.value = res.list
  })
}

// 新增/编辑分类提交
function commitTreeNode() {
  const operateType = operateNodeTitle.value.includes('新增') ? 'create' : 'update'
  let data = operateType === 'create' ? {} : state.currentNode
  if (operateNodeTitle.value.includes('新增')) {
    data = {
      label: state.currentNode.label,
      value: treeData.value.length > 0 ? String(Number(treeData.value[0].value) + 1) : '1',
      dictType: 'countryside_image_text_type',
      status: 0,
      sort: treeData.value.length > 0 ? Number(treeData.value[0].value) + 1 : 1
    }
  }
  globalApi.operateDictData(operateType, data).then(() => {
    message.success('分类操作成功')
    operateNodeVisible.value = false
    getDictData()
  })
}
function handleClick(value) {
  noticeType.value = value.id
  getNotificationAnnouncement()
}
// 获取通知公告列表
function getNotificationAnnouncement() {
  const data = {
    pageNo: currentPage.value,
    pageSize: pageSize.value,
    topic: topic.value,
    noticeType: noticeType.value
  }
  notificationAnnouncementApi
    .operateNotificationAnnouncement('page', data, null)
    .then((res) => {
      res.list.forEach((item) => {
        item.isDisplayViewer = Boolean(item.isDisplayViewer)
      })
      tableData.value = res.list
      total.value = res.total
      if (tableData.value.length === 0) {
        value.value = true
      } else {
        value.value = false
      }
      loading.value = false
    })
    .catch((error) => {
      loading.value = false
    })
}

// 新增/编辑表格行
function operateNotificationAnnouncement() {
  dynamicForm.value.validateForm(() => {
    const type = dialogTitle.value.includes('新增') ? 'create' : 'update'
    let data = dynamicForm.value.getFormData()
    let files = data.files ? data.files.map((item) => item.id) : []
    notificationAnnouncementApi
      .operateNotificationAnnouncement(
        type,
        { ...data, files, isTopping: 0, isDisplayViewer: 0 },
        null
      )
      .then(() => {
        message.success(`${dialogTitle.value}成功`)
        operateVisible.value = false
        getNotificationAnnouncement()
      })
  })
}

// 删除表格行
function delNotificationAnnouncement(type, row) {
  if (type === 'batch' && !rowSelection.value.length) {
    return message.warning('请先选择需要删除的数据')
  }
  ElMessageBox.confirm(`确认删除吗？`, '警告', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消'
  }).then(() => {
    let ids = type === 'single' ? [row.id] : rowSelection.value.map((r) => r.id)
    const params = {
      ids: ids.join(',')
    }
    notificationAnnouncementApi.operateNotificationAnnouncement('delete', null, params).then(() => {
      message.success('删除数据成功')
      getNotificationAnnouncement()
    })
  })
}

// 新增/编辑表格行事件
async function operateRow(type, row) {
  if (type === 'add') {
    state.formData = {}
  } else {
    let data = await notificationAnnouncementApi.getOperateNotificationAnnouncement(row.id)
    state.formData = data
    state.formData.files = data.fileDOList
  }
  dialogTitle.value = `${type === 'add' ? '新增' : '编辑'}图文`
  operateVisible.value = true
  console.log('row', row)
}

// 置顶
function topRow(row) {
  notificationAnnouncementApi
    .operateNotificationAnnouncement(
      'update',
      {
        ...row,
        isTopping: row.isTopping == 1 ? 0 : 1,
        isDisplayViewer: row.isDisplayViewer ? 1 : 0
      },
      null
    )
    .then(() => {
      row.isTopping == 1 ? message.success('取消置顶操作成功') : message.success('置顶操作成功')
      getNotificationAnnouncement()
    })
}

function topChange(row) {
  notificationAnnouncementApi
    .operateNotificationAnnouncement(
      'update',
      {
        ...row,
        isDisplayViewer: row.isDisplayViewer ? 1 : 0
      },
      null
    )
    .then(() => {
      row.isDisplayViewer
        ? message.success('大屏展示操作成功')
        : message.success('取消大屏展示操作成功')

      getNotificationAnnouncement()
    })
}

// 新增/编辑分类事件
function operateNode(type, row) {
  operateNodeTitle.value = `${type === 'add' ? '新增' : '编辑'}分类`
  state.currentNode = type === 'add' ? { label: '' } : cloneDeep(row)
  operateNodeVisible.value = true
}

// 删除分类
function delTreeNode(row) {
  ElMessageBox.confirm(`确认删除分类【${row.label}】吗？删除该通知分类会删除其下面所有的通知公告内容，请谨慎操作`, '警告', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消'
  }).then(() => {
    const params = {
      id: row.id
    }
    globalApi.delDictData(params).then(() => {
      message.success('删除成功')
    })
  })
}

// 表格选择事件
function handleSelectionChange(val) {
  console.log('selection', val)

  rowSelection.value = val
}

// 表格分类字段映射
function imageTextTypeRelate(row) {
  let content = ''
  treeData.value.forEach((t) => {
    if (t.id === row.imageTextType) {
      content = t.label
    }
  })
  return content
}

function handleReset() {
  currentPage.value = 1
  pageSize.value = 20
  topic.value = ''
  getNotificationAnnouncement()
}

onMounted(() => {
  getDictData()
  getNotificationAnnouncement()
})
</script>

<style lang="scss" scoped>
@import url('../styles/global.css');

.operate {
  display: flex;
}

.content {
  display: flex;

  .left {
    width: 280px;
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    border: 1px solid #efefef;
    margin-right: 16px;
  }

  .right {
    width: 100%;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

:deep(.custom-tree-node span:nth-child(1)) {
  width: 150px;
  overflow: hidden;
  white-space: normal;
}

:deep(.el-tree-node__content) {
  height: max-content;
}

:deep(.el-tree-node) {
  margin-bottom: 10px;
}

.btn {
  width: 80px;
  height: 30px;
  line-height: 20px;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}

.btnreset {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(187, 187, 187, 1);
  color: rgba(142, 142, 142, 1);
}

.btnsearch {
  background-color: #cc352f;
  color: rgba(255, 255, 255, 1);
  border: 1px solid #cc352f;
}

.btn:hover {
  opacity: 0.8;
}

.btnhover:hover {
  opacity: 0.8;
}

::v-deep .el-form-item__label {
  font-weight: 500;
}

::v-deep .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 1px #cc352f;
}
</style>
